import 'package:xbaistack/page/Home.dart';
import 'package:xbaistack/page/my.dart';
import 'package:xbaistack/page/refresh_demo.dart';
import 'package:xbaistack/widget/lazy_indexed_stack.dart';
import 'package:xbaistack/widget/my_button.dart';
import 'package:flutter/material.dart';

class BottomMenuBarPage extends StatefulWidget {
  const BottomMenuBarPage({super.key});
  @override
  State<BottomMenuBarPage> createState() => _PageState();
}

class _PageState extends State<BottomMenuBarPage> {
  // 创建一个变量用于记录当前激活的菜单下标
  // 初始值即为默认激活的菜单下标
  int currentIndex = 0;
  late final LazyIndexedStackController controller;
  final List<Widget> pages = <Widget>[const HomePage(), const MyPage()];

  void btnClick(MyButtons widget) {
    print(widget.text);
    setState(() {
      // message = "点击了按钮";
    });
  }

  // 菜单项列表（可以单独定义，也可以直接在属性中定义，主要看哪个方便）
  final List<BottomNavigationBarItem> items = const <BottomNavigationBarItem>[
    BottomNavigationBarItem(
      icon: Icon(Icons.home),
      label: "主页",
      activeIcon: Icon(Icons.access_alarm),
    ),
    // BottomNavigationBarItem(icon: Icon(Icons.message), label: "消息"),
    // BottomNavigationBarItem(icon: Icon(Icons.grade), label: "收藏"),
    BottomNavigationBarItem(icon: Icon(Icons.person), label: "我"),
  ];

  // NOTE：
  // | → setState()：用于通知 UI 重绘
  // | → 每次重绘都会调用 build 方法，由于变量已经更新，所以 build 重绘时就会把最新的数据绘制到当前页面上；
  void changeIndex(int activeIndex) {
    if (currentIndex != activeIndex) {
      controller.changeIndex(activeIndex);
      setState(() => currentIndex = activeIndex);
      // 如果点击的菜单项已经是当前激活的菜单项，则不需要更新状态
    } else {
      final page = pages[activeIndex];
      if (page is RefreshDemoPage) {
        // 如果是刷新页面，则调用其刷新方法
        (page as RefreshDemoPage).toRefresh();
      }
    }
    // Lambda 简洁形式：() => expression

    // 完整写法：
    // setState(() {
    //  currentIndex = activeIndex;
    // });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    controller = LazyIndexedStackController(children: pages);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("底部导航菜单")),
      body: LazyIndexedStack(controller: controller),
      bottomNavigationBar: BottomNavigationBar(
        items: items,
        onTap: changeIndex,
        currentIndex: currentIndex,
        selectedItemColor: Colors.redAccent,
      ),
    );
  }
}
